package com.tanhua.sso.service;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.tanhua.sso.config.AliyunSMSConfig;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
@Slf4j
public class SmsService {



    @Autowired
    private AliyunSMSConfig aliyunSMSConfig;

    /*
         redisTemplate跟jdbcTemplate类型.内部封装了对Redis的一些操作
         redisTemplate与StringRedisTemplate的区别:
                             --使用StringRedisTemplate才能获取Redis当中的数据值是以可读的形式显示出来的时候
                             --redisTemplate存入redis中是以字节数组显示
     */
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public static final String CHECK_CODE = "CHECK_CODE";

    /**
     * 发送短信验证码
     *
     * @param mobile
     * @return
     */
    public String sendSms(String mobile) {
        DefaultProfile profile = DefaultProfile.getProfile(this.aliyunSMSConfig.getRegionId(),
                this.aliyunSMSConfig.getAccessKeyId(), this.aliyunSMSConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        String code = RandomUtils.nextInt(100000, 999999) + "";

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(this.aliyunSMSConfig.getDomain());
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", this.aliyunSMSConfig.getRegionId());
        request.putQueryParameter("PhoneNumbers", mobile); //目标手机号
        request.putQueryParameter("SignName", this.aliyunSMSConfig.getSignName()); //签名名称
        request.putQueryParameter("TemplateCode", this.aliyunSMSConfig.getTemplateCode()); //短信模板code
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");//模板中变量替换
        try {
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            if (StringUtils.contains(data, "\"Message\":\"OK\"")) {
                return code;
            }
            log.info("发送短信验证码失败~ data = " + data);
        } catch (Exception e) {
            log.error("发送短信验证码失败~ mobile = " + mobile, e);
        }
        return null;
    }

    /**
     * 发送短信验证码
     * 实现：发送完成短信验证码后，需要将验证码保存到redis中
     *
     * @param phone
     * @return
     */
    public ErrorResult sendCheckCode(String phone) {

        //1.定义存入redis中的手机号形式CHECK_CODE17602026868
        String redisKey = CHECK_CODE + phone;

        //2.先判断该手机号发送的验证码是否还未失效
        if (this.redisTemplate.hasKey(redisKey)) {
            //2.1如果redis中还存在手机号,说明上一次发送的手机号验证码还未失效
            String msg = "上一次发送的验证码还未失效！";

            //2.2返回错误码和错误信息
            return ErrorResult.builder().errCode("000001").errMessage(msg).build();
        }

        //String code = this.sendSms(phone);
        //3.为了测试方便,不调用发送短信验证码的服务,设置一个固定的验证码code = "123456"
        String code = "123456";

        //4.通过返回的验证码code是否为空,判断验证码是否发送成功
        if (StringUtils.isEmpty(code)) {
            //4.1若为空,则发送短信验证码失败,定义错误信息
            String msg = "发送短信验证码失败！";

            //4.2返回错误码和错误信息
            return ErrorResult.builder().errCode("000000").errMessage(msg).build();
        }

        //5.上述判断条件均不匹配说明短信发送成功，将验证码保存到redis中，有效期为5分钟
        /*
            redisKey:CHECK_CODE17602026868
            code:123456
            Duration.ofMinutes(5):设置过期时间为5分钟
         */
        this.redisTemplate.opsForValue().set(redisKey, code, Duration.ofMinutes(5));

        //6.若成功接收到短信验证码,则返回为空,由于接收方是把返回的信息和null相对比,判断是否出错
        return null;
    }
}